import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useSysUserStore } from '@/stores/sysUser'
import router from '@/router'

// 创建axios实例
const httpInstance = axios.create({
  baseURL: '', // 移除baseURL，因为我们会在API中使用完整的路径
  timeout: 5000
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  try {
    const userStore = useSysUserStore();
    // 更安全地访问 token
    const token = userStore.$state?.userInfo?.userInfoVO?.token || 
                  userStore.userInfo?.userInfoVO?.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
  } catch (e) {
    console.error('获取用户信息失败:', e);
    // 忽略
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
// 响应拦截器
httpInstance.interceptors.response.use(
  res => {
    // 假设后端返回 { code, msg, data }
    if (res.data.code && res.data.code !== 0) {
      ElMessage({
        type: 'warning',
        message: res.data.msg || '业务异常'
      })
      // 主动抛出错误，让业务 catch
      return Promise.reject(res.data)
    }
    return res.data
  },
  e => {
    console.log('请求错误:', e);
    if(e.response.status === 401) {
      //清除本地数据
      const userStore = useSysUserStore();
      // 更安全地调用 clearUserInfo
      if (userStore && typeof userStore.clearUserInfo === 'function') {
        userStore.clearUserInfo();
      }

      // 可以在这里跳转到登录页面
      router.push('/login')
    }
    return Promise.reject(e)
  }
)


const get = (url, params = {}, config = {}) => {
  return httpInstance.get(url, { params, ...config })
}

const put = (url, data = {}, config = {}) => {
  return httpInstance.put(url, data, config)
}

const del = (url, config = {}) => {
  return httpInstance.delete(url, config)
}

// 封装post请求
const post = (url, data = {}, config = {}) => {
  console.log('post调用', url, data)
  return httpInstance.post(url, data, config)
}

// 创建默认导出，这样API文件可以正常导入
export default {
  get,
  post,
  put,
  del,
  httpInstance
}

// 同时保留命名导出，以保持向后兼容
export {
  get,
  post,
  put,
  del,
  httpInstance
}